#include "BlockQueue.hpp"
#include "tesk.hpp"
#include <time.h>

int myadd(int x, int y)
{
    return x + y;
}

void *consumer(void *args)
{
    BlockQueue<Task> *bq = (BlockQueue<Task> *)args;

    while (true)
    {
        // 获取任务
        Task t;
        bq->pop(&t);
        // 完成任务
        cout << pthread_self() << "————consumer:  " << t._x << "+" << t._y << "=" << t() << endl;
        // cout << "————消费数据：" << a << endl;
        sleep(1);
    }

    return nullptr;
}
void *productor(void *args)
{
    BlockQueue<Task> *bq = (BlockQueue<Task> *)args;

    // int a = 1;
    while (true)
    {
        // 制作任务
        int x = rand() % 10 + 1;
        usleep(10000);
        int y = rand() % 5 + 1;

        Task t(x, y, myadd);
        // 生产任务
        bq->push(t);
        cout << pthread_self() << "productor:  " << t._x << "+" << t._y << "=  ？ " << endl;
    }

    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid() ^ 0x238723);
    BlockQueue<Task> *bqueue = new BlockQueue<Task>();
    pthread_t c[2], p[2];
    pthread_create(&c[0], nullptr, consumer, bqueue);
    pthread_create(&c[1], nullptr, consumer, bqueue);
    pthread_create(&p[0], nullptr, productor, bqueue);
    pthread_create(&p[1], nullptr, productor, bqueue);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);

    delete bqueue;
    return 0;
}